{% extends "bootstrap/base.html" %}

{% block title %}翻译记录管理 - 小於菟 MTranServer{% endblock %}

{% block head %}
{{ super() }}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
{% endblock %}

{% block content %}
<div class="container mt-4">
    <h1 class="mb-4">📊 翻译管理</h1>

    <div class="card mb-4">
        <div class="card-body">
            <div class="form-group">
                <label>管理员令牌:</label>
                <input type="password" class="form-control" id="adminToken" placeholder="输入管理员令牌">
            </div>
            <button class="btn btn-primary" onclick="loadTranslationManage()">加载管理界面</button>
        </div>
    </div>

    <div id="recordsSection" style="display: none;">
        <!-- 在管理员面板添加授权码管理部分 -->
        <div class="card mt-4">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h3 class="mb-0">授权码管理</h3>
            </div>
            <div class="card-body">
                <button class="btn btn-success mb-3" onclick="generateAuthCode()">
                    <i class="fas fa-plus-circle"></i> 生成新授权码
                </button>

                <div id="newCodeContainer" class="alert alert-success" style="display: none;">
                    <h5>新授权码：</h5>
                    <div class="d-flex justify-content-between align-items-center">
                        <code id="newAuthCode" class="font-weight-bold" style="font-size: 1.2rem;"></code>
                        <button class="btn btn-sm btn-outline-secondary" onclick="copyAuthCode()">
                            <i class="far fa-copy"></i> 复制
                        </button>
                    </div>
                    <small class="text-muted">此码今日有效，使用后自动失效</small>
                </div>

                <div class="table-responsive mt-4">
                    <table class="table table-striped">
                        <thead>
                            <tr>
                                <th>授权码</th>
                                <th>创建时间</th>
                                <th>状态</th>
                                <th>使用IP</th>
                                <th>使用时间</th>
                            </tr>
                        </thead>
                        <tbody id="authCodesTable"></tbody>
                    </table>
                </div>
            </div>
        </div>
        <div class="card mb-4">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h3 class="mb-0">翻译记录</h3>
                <button class="btn btn-info" onclick="exportTranslationRecords()">
                    <i class="fas fa-download"></i> 导出记录
                </button>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-striped">
                        <thead>
                            <tr>
                                <th>IP地址</th>
                                <th>原文</th>
                                <th>译文</th>
                                <th>源语言</th>
                                <th>目标语言</th>
                                <th>时间</th>
                            </tr>
                        </thead>
                        <tbody id="translationRecords"></tbody>
                    </table>
                </div>
            </div>
        </div>

        <div class="card">
            <div class="card-header">
                <h3 class="mb-0">访问限制</h3>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-striped">
                        <thead>
                            <tr>
                                <th>IP地址</th>
                                <th>访问次数</th>
                                <th>最后访问时间</th>
                            </tr>
                        </thead>
                        <tbody id="accessLimits"></tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    function loadAuthCodes(token) {
        fetch(`/admin/auth_codes?token=${token}`)
            .then(response => response.json())
            .then(data => {
                const authCodesTable = document.getElementById('authCodesTable');
                authCodesTable.innerHTML = '';

                data.auth_codes.forEach(code => {
                    const row = document.createElement('tr');
                    const status = code.used ?
                        `<span class="badge badge-danger">已使用</span>` :
                        `<span class="badge badge-success">未使用</span>`;

                    row.innerHTML = `
                        <td><code>${code.code}</code></td>
                        <td>${code.created_at}</td>
                        <td>${status}</td>
                        <td>${code.used_by_ip || '-'}</td>
                        <td>${code.used_at || '-'}</td>
                    `;
                    authCodesTable.appendChild(row);
                });
            })
            .catch(error => {
                console.error('加载授权码失败:', error);
                alert('加载授权码失败: ' + error.message);
            });
    }
    function generateAuthCode() {
        const token = document.getElementById('adminToken').value;
        if (!token) {
            alert('请先输入管理员令牌');
            return;
        }

        fetch(`/admin/generate_code?token=${token}`, {
            method: "POST"
        })
        .then(res => res.json())
        .then(data => {
            if (data.code) {
                document.getElementById('newAuthCode').innerText = data.code;
                document.getElementById('newCodeContainer').style.display = 'block';
                loadAuthCodes(token);
            } else {
                alert('生成失败: ' + (data.error || '未知错误'));
            }
        })
        .catch(error => {
            alert('请求失败: ' + error);
        });
    }

    function copyAuthCode() {
        const code = document.getElementById('newAuthCode').innerText;
        navigator.clipboard.writeText(code)
            .then(() => {
                alert('授权码已复制到剪贴板');
            })
            .catch(err => {
                alert('复制失败: ' + err);
            });
    }
    function loadTranslationManage() {
        const token = document.getElementById('adminToken').value;
        if (!token) {
            alert('请输入管理员令牌');
            return;
        }

        fetch(`/admin/translation_records?token=${token}`)
            .then(response => {
                if (response.status === 401) {
                    alert('令牌无效或未授权');
                    throw new Error('Unauthorized');
                }
                return response.json();
            })
            .then(data => {
                if (data.error) {
                    alert('加载失败: ' + data.error);
                    return;
                }

                // 渲染翻译记录
                const recordsTable = document.getElementById('translationRecords');
                recordsTable.innerHTML = '';

                data.translation_records.forEach(record => {
                    const row = document.createElement('tr');
                    row.innerHTML = `
                        <td>${record.ip}</td>
                        <td>${record.source_text}</td>
                        <td>${record.translated_text}</td>
                        <td>${record.source_lang}</td>
                        <td>${record.target_lang}</td>
                        <td>${record.timestamp}</td>
                    `;
                    recordsTable.appendChild(row);
                });

                // 渲染访问限制
                const limitsTable = document.getElementById('accessLimits');
                limitsTable.innerHTML = '';

                data.access_limits.forEach(limit => {
                    const row = document.createElement('tr');
                    row.innerHTML = `
                        <td>${limit.ip}</td>
                        <td>${limit.count}</td>
                        <td>${limit.last_access}</td>
                    `;
                    limitsTable.appendChild(row);
                });

                // 显示结果区域
                document.getElementById('recordsSection').style.display = 'block';
                loadAuthCodes(token);
            })
            .catch(error => {
                console.error('Error:', error);
            });
    }
    
    function exportAuthCodes() {
        const token = document.getElementById('adminToken').value;
        if (!token) {
            alert('请先输入管理员令牌');
            return;
        }
        
        // 添加加载状态
        const originalText = this.innerHTML;
        this.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 导出中...';
        this.disabled = true;
        
        // 调用导出接口
        window.location.href = `/admin/export_auth_codes?token=${token}`;
        
        // 恢复按钮状态
        setTimeout(() => {
            this.innerHTML = originalText;
            this.disabled = false;
        }, 2000);
    }
    
    function exportTranslationRecords() {
        const token = document.getElementById('adminToken').value;
        if (!token) {
            alert('请先输入管理员令牌');
            return;
        }
        
        // 添加加载状态
        const originalText = this.innerHTML;
        this.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 导出中...';
        this.disabled = true;
        
        // 调用导出接口
        window.location.href = `/admin/export_translation_records?token=${token}`;
        
        // 恢复按钮状态
        setTimeout(() => {
            this.innerHTML = originalText;
            this.disabled = false;
        }, 2000);
    }
</script>

<style>
    .table th {
        background-color: #f8f9fa;
        font-weight: 600;
    }

    .table-striped tbody tr:nth-of-type(odd) {
        background-color: rgba(0, 0, 0, 0.02);
    }

    .card {
        border-radius: 10px;
        box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
        border: none;
        margin-bottom: 25px;
    }

    .card-header {
        background-color: #f8f9fa;
        border-bottom: 1px solid rgba(0, 0, 0, 0.08);
        padding: 15px 20px;
        border-top-left-radius: 10px !important;
        border-top-right-radius: 10px !important;
    }
    .badge {
        padding: 5px 10px;
        border-radius: 4px;
        font-weight: normal;
    }
    .badge-success {
        background-color: #28a745;
        color: white;
    }
    .badge-danger {
        background-color: #dc3545;
        color: white;
    }
    .badge-warning {
        background-color: #ffc107;
        color: #212529;
    }
</style>
{% endblock %}